package com.slh.touchandroid.service;

import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.ActivityManager;
import android.app.ActivityManager.MemoryInfo;
import android.app.ActivityManager.RecentTaskInfo;
import android.app.ActivityManager.RunningAppProcessInfo;
import android.app.Notification;
import android.app.PendingIntent;
import android.app.Service;
import android.bluetooth.BluetoothAdapter;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.content.res.Configuration;
import android.database.ContentObserver;
import android.graphics.PixelFormat;
import android.graphics.Point;
import android.graphics.drawable.Drawable;
import android.media.AudioManager;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.net.wifi.WifiManager;
import android.os.Build;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Handler;
import android.os.IBinder;
import android.os.Process;
import android.provider.Settings.System;
import android.support.v4.content.IntentCompat;
import android.view.Display;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnLongClickListener;
import android.view.View.OnTouchListener;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.view.WindowManager.LayoutParams;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ViewFlipper;

import com.slh.touchandroid.R;
import com.slh.touchandroid.activity.BrowserActivity;
import com.slh.touchandroid.activity.DeviceActivity;
import com.slh.touchandroid.activity.TouchActivity;
import com.slh.touchandroid.db.DBHelper;
import com.slh.touchandroid.model.AppInfo;
import com.slh.touchandroid.model.FloatInfo;
import com.slh.touchandroid.utils.AppUtils;
import com.slh.touchandroid.utils.CONFIG;
import com.slh.touchandroid.utils.Logging;
import com.slh.touchandroid.utils.Utils;

public class TouchService extends Service implements OnClickListener,
		OnLongClickListener {
	// ==========================================================================
	private static final String ACTION_START_ANDROID_TOUCH = "com.slh.touchandroid.service.TouchService.ACTION_START_ANDROID_TOUCH";
	private static final int MAX_9_APPS = 9;
	private static final int MAX_TASKBAR_HEIGHT = 1000;
	private WindowManager mWindowManager;
	private LayoutParams mTouchIconParams;
	private LayoutParams mTouchViewParams;
	private View mTouchIcon;
	private View mTouchMainView;
	private float mX = 0;
	private float mY = 0;
	private ImageButton mImgWifi;
	private ImageButton mImgData;
	private ImageButton mImgBluetooth;
	private ImageButton mImgAirplane;
	private ImageButton mImgGps;
	private ImageButton mImgRotate;
	private ImageButton mImgSound;

	private ListView mLvInstalledApps;
	private AppsAdapter mAdtInstalledApps;
	private ArrayList<AppInfo> mInstalledApps;

	private AppsAdapter mAdtRunningApps;
	private ArrayList<AppInfo> mRunningApps;
	private int mFlagWindow;
	private ImageButton mImgAvatar;
	private TextView mTvUser;
	private BroadcastReceiver mUpdateFavoriteReceiver = new BroadcastReceiver() {

		@Override
		public void onReceive(Context context, Intent intent) {
			Logging.log(intent);
			// setFavoriteApp();
			String action = intent.getAction();
			if (CONFIG.BROADCAST.ACTION_FAVORITE_APP_CHANGED.equals(action)) {
				setFavoriteApp();
			} else if (CONFIG.BROADCAST.ACTION_MAIN_PANEL_CHANGED
					.equals(action)) {
				loadMain(mTouchMainView);
				try {
					updateView(mTouchMainView, mTouchViewParams);
				} catch (Exception e) {
					// TODO: handle exception
				}
			} else if (CONFIG.BROADCAST.ACTION_SUB_PANEL_CHANGED.equals(action)) {
				loadSub(mTouchMainView);
				try {
					updateView(mTouchMainView, mTouchViewParams);
				} catch (Exception e) {
					// TODO: handle exception
				}
			}

		}

	};

	private void updateView(View view, LayoutParams params) {
		try {
			mWindowManager.addView(view, params);
		} catch (Exception e) {
			mWindowManager.updateViewLayout(view, params);
		}
	}

	private void showView(View view) {

		View hidenView = view == mTouchMainView ? mTouchIcon : mTouchMainView;
		hidenView.setVisibility(View.GONE);
		view.setVisibility(View.VISIBLE);

	}

	private BroadcastReceiver mScreenOrientationReceiver = new BroadcastReceiver() {

		@Override
		public void onReceive(Context context, Intent intent) {
			// transit(mTouchFavoriteView, mTouchViewParams, mTouchIcon,
			// mTouchMainView, mTouchSubView, mTouchFavoriteView);
			// setMainViewParams();
			try {
				mWindowManager.updateViewLayout(mTouchMainView,
						mTouchViewParams);
			} catch (Exception e) {
				// TODO: handle exception
			}

		}
	};

	private BroadcastReceiver mReceiver = new BroadcastReceiver() {

		@Override
		public void onReceive(Context context, Intent intent) {
			String action = intent.getAction();
			Logging.log(action);
			if (CONFIG.BROADCAST.ACTION_FLOATING_ICON_SETTINFS.equals(action)) {
				boolean isShown = intent.getBooleanExtra(
						CONFIG.BROADCAST.EXTRA_FLOATING_ICON_SETTINFS, true);
				if (!isShown) {
					removeAllView();
				} else {
					mWindowManager.addView(mTouchIcon, mTouchIconParams);
				}
			} else if (CONFIG.BROADCAST.ACTION_SHOW_ICON_ON_LOCK_SETTINFS
					.equals(action)) {
				boolean isShown = intent
						.getBooleanExtra(
								CONFIG.BROADCAST.EXTRA_SHOW_ICON_ON_LOCK_SETTINFS,
								true);
				if (!isShown) {
					mFlagWindow = mFlagWindow | 0x00000;
				} else {
					mFlagWindow = mFlagWindow
							| LayoutParams.FLAG_SHOW_WHEN_LOCKED;
				}
				mTouchIconParams.flags = mFlagWindow;
				mTouchViewParams.flags = mFlagWindow;
				mWindowManager.updateViewLayout(mTouchIcon, mTouchIconParams);
			} else if (WifiManager.WIFI_STATE_CHANGED_ACTION.equals(action)) {
				int state = intent.getIntExtra(WifiManager.EXTRA_WIFI_STATE,
						WifiManager.WIFI_STATE_DISABLED);
				mTouchMainView.findViewWithTag(getString(R.string.tag_wifi))
						.setSelected(state == WifiManager.WIFI_STATE_ENABLED);
				updateView(mTouchMainView, mTouchViewParams);
			} else if (Intent.ACTION_AIRPLANE_MODE_CHANGED.equals(action)) {
				boolean state = intent.getBooleanExtra("state", false);
				mTouchMainView
						.findViewWithTag(getString(R.string.tag_airplane))
						.setSelected(state);
				updateView(mTouchMainView, mTouchViewParams);
			} else if (ConnectivityManager.CONNECTIVITY_ACTION.equals(action)) {
				NetworkInfo netInfo = intent
						.getParcelableExtra(WifiManager.EXTRA_NETWORK_INFO);
				if (netInfo != null
						&& netInfo.getType() == ConnectivityManager.TYPE_MOBILE) {
					mTouchMainView
							.findViewWithTag(getString(R.string.tag_data))
							.setSelected(netInfo.isConnected());
					updateView(mTouchMainView, mTouchViewParams);
				}

			} else if (BluetoothAdapter.ACTION_STATE_CHANGED.equals(action)) {
				int state = intent.getIntExtra(BluetoothAdapter.EXTRA_STATE,
						BluetoothAdapter.STATE_OFF);
				mTouchMainView.findViewWithTag(
						getString(R.string.tag_bluetooth)).setSelected(
						state == BluetoothAdapter.STATE_ON);
				updateView(mTouchMainView, mTouchViewParams);
			} else if (AudioManager.RINGER_MODE_CHANGED_ACTION.equals(action)) {
				int state = intent.getIntExtra(AudioManager.EXTRA_RINGER_MODE,
						AudioManager.RINGER_MODE_NORMAL);
				ImageButton imgSound = (ImageButton) mTouchMainView
						.findViewWithTag(getString(R.string.tag_bluetooth));
				switch (state) {
				case AudioManager.RINGER_MODE_NORMAL:
					imgSound.setImageResource(R.drawable.btn_volume_on);
					break;
				case AudioManager.RINGER_MODE_SILENT:
					imgSound.setImageResource(R.drawable.btn_volume_mute);
					break;
				case AudioManager.RINGER_MODE_VIBRATE:
					imgSound.setImageResource(R.drawable.btn_vibrate);
					break;
				default:
					break;
				}
				updateView(mTouchMainView, mTouchViewParams);
			} else if (CONFIG.BROADCAST.ACTION_FLOAT_ICON_RESOURCE_CHANGED
					.equals(action)) {
				int resId = intent.getIntExtra(
						CONFIG.BROADCAST.EXTRA_FLOAT_ICON_RESOURCE,
						R.drawable.ic_android0);
				((ImageButton) mTouchIcon).setImageResource(resId);
				updateView(mTouchIcon, mTouchIconParams);
			}

		}
	};

	private ContentObserver mObserver = new ContentObserver(new Handler()) {
		public void onChange(boolean selfChange, android.net.Uri uri) {
			if (System.getUriFor(System.ACCELEROMETER_ROTATION).equals(uri)) {
				int state = System.getInt(getContentResolver(),
						System.ACCELEROMETER_ROTATION, 0);
				mTouchMainView.findViewWithTag(getString(R.string.tag_rotate))
						.setSelected(state == 1);
				updateView(mTouchMainView, mTouchViewParams);
			}
		};
	};

	// ==========================================================================
	public static void startAndroidTouch(Context context) {
		Intent service = new Intent(context, TouchService.class);
		service.setAction(ACTION_START_ANDROID_TOUCH);
		context.startService(service);
	}

	@Override
	public IBinder onBind(Intent intent) {
		throw new UnsupportedOperationException("Not yet implemented");
	}

	@Override
	public void onCreate() {
		registerReceiver(mScreenOrientationReceiver, new IntentFilter(
				Intent.ACTION_CONFIGURATION_CHANGED));
		IntentFilter panelFilter = new IntentFilter();
		panelFilter.addAction(CONFIG.BROADCAST.ACTION_FAVORITE_APP_CHANGED);
		panelFilter.addAction(CONFIG.BROADCAST.ACTION_MAIN_PANEL_CHANGED);
		panelFilter.addAction(CONFIG.BROADCAST.ACTION_SUB_PANEL_CHANGED);

		registerReceiver(mUpdateFavoriteReceiver, panelFilter);
		IntentFilter filter = new IntentFilter(
				CONFIG.BROADCAST.ACTION_FLOATING_ICON_SETTINFS);
		filter.addAction(CONFIG.BROADCAST.ACTION_SHOW_ICON_ON_LOCK_SETTINFS);
		filter.addAction(Intent.ACTION_AIRPLANE_MODE_CHANGED);
		filter.addAction(WifiManager.WIFI_STATE_CHANGED_ACTION);
		filter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
		filter.addAction(BluetoothAdapter.ACTION_STATE_CHANGED);
		filter.addAction(AudioManager.RINGER_MODE_CHANGED_ACTION);
		filter.addAction(CONFIG.BROADCAST.ACTION_FLOAT_ICON_RESOURCE_CHANGED);
		registerReceiver(mReceiver, filter);
		Uri uri = System.getUriFor(System.ACCELEROMETER_ROTATION);
		getContentResolver().registerContentObserver(uri, true, mObserver);
		init();
		super.onCreate();
	}

	@Override
	public void onDestroy() {
		unregisterReceiver(mUpdateFavoriteReceiver);
		unregisterReceiver(mScreenOrientationReceiver);
		unregisterReceiver(mReceiver);
		getContentResolver().unregisterContentObserver(mObserver);
		super.onDestroy();
	}

	@Override
	public int onStartCommand(Intent intent, int flags, int startId) {
		if (intent == null) {
			return START_STICKY;
		}
		String action = intent.getAction();
		if (ACTION_START_ANDROID_TOUCH.equals(action)) {
			startForeGroundService();
		}
		return START_STICKY;
	}

	// ==========================================================================
	@Override
	public void onClick(View v) {
		String tag = (String) v.getTag();
		if (getString(R.string.tag_back).equalsIgnoreCase(tag)) {
			// transit(mTouchMainView, mTouchViewParams, mTouchMainView);
		} else if (getString(R.string.tag_camera).equalsIgnoreCase(tag)) {
			// showView(mTouchIcon);
			showView(mTouchIcon);
			TouchActivity.start(getApplicationContext(),
					TouchActivity.ACTION_FINISH);
			new Handler().postDelayed(new Runnable() {
				@Override
				public void run() {
					AppUtils.launchCameraApp(getApplicationContext());
				}
			}, 500);
		} else if (getString(R.string.tag_help).equalsIgnoreCase(tag)) {
			showView(mTouchIcon);
			TouchActivity.start(getApplicationContext());
		} else if (getString(R.string.tag_home).equalsIgnoreCase(tag)) {
			showView(mTouchIcon);
			AppUtils.launchHomeApp(getApplicationContext());
		} else if (getString(R.string.tag_icon).equalsIgnoreCase(tag)) {
			showView(mTouchMainView);
		} else if (getString(R.string.tag_light).equalsIgnoreCase(tag)) {
			showView(mTouchIcon);
			TouchActivity.start(getApplicationContext(),
					TouchActivity.ACTION_LIGHT);
		} else if (getString(R.string.tag_lock).equalsIgnoreCase(tag)) {
			showView(mTouchIcon);
			CONFIG.ADMIN_DEVICE.addDeviceAdmin(getApplicationContext());
		} else if (getString(R.string.tag_mirror).equalsIgnoreCase(tag)) {
			showView(mTouchIcon);
			TouchActivity.start(getApplicationContext(),
					TouchActivity.ACTION_MIRROR);
		} else if (getString(R.string.tag_more).equalsIgnoreCase(tag)) {
			showView(mTouchIcon);
			// TouchActivity.start(getApplicationContext(),
			// TouchActivity.ACTION_RUNNING_APP);
			// killApp(TouchService.this);
			AppUtils.launchActivity(getApplicationContext(),
					DeviceActivity.class);
		} else if (getString(R.string.tag_recent).equalsIgnoreCase(tag)) {
			showView(mTouchIcon);
			AppUtils.launchRecentApps();
		} else if (getString(R.string.tag_vibrate).equalsIgnoreCase(tag)) {
			Utils.setSoundMode(getApplicationContext(),
					AudioManager.RINGER_MODE_VIBRATE);
		} else if (getString(R.string.tag_volume_mute).equalsIgnoreCase(tag)) {
			Utils.setSoundMode(getApplicationContext(),
					AudioManager.RINGER_MODE_SILENT);
		} else if (getString(R.string.tag_volume_on).equalsIgnoreCase(tag)) {
			Utils.setSoundMode(getApplicationContext(),
					AudioManager.RINGER_MODE_NORMAL);
		} else if (getString(R.string.tag_app).equalsIgnoreCase(tag)) {
			showView(mTouchIcon);
			TouchActivity.start(getApplicationContext(),
					TouchActivity.ACTION_INSTALLED_APP);
		} else if (getString(R.string.tag_gps).equalsIgnoreCase(tag)) {
			showView(mTouchIcon);
			AppUtils.launchGPSSettings(getApplicationContext());
		} else if (getString(R.string.tag_settings).equalsIgnoreCase(tag)) {
			showView(mTouchIcon);
			AppUtils.launchSettingsApp(getApplicationContext());
		} else if (getString(R.string.tag_folder).equalsIgnoreCase(tag)) {
			showView(mTouchIcon);
			AppUtils.launchActivity(this, BrowserActivity.class);
		} else if (getString(R.string.tag_data).equalsIgnoreCase(tag)) {
			showView(mTouchIcon);
			AppUtils.launchSettingsApp(getApplicationContext());
		} else if (getString(R.string.tag_wifi).equalsIgnoreCase(tag)) {
			Utils.WIFI.toggleWifi(getApplicationContext());
		} else if (getString(R.string.tag_bluetooth).equalsIgnoreCase(tag)) {
			Utils.Bluetooth
					.toggleBluetoothEnabled(getApplicationContext());
		} else if (getString(R.string.tag_airplane).equalsIgnoreCase(tag)) {
			Utils.Airplane.toggleAirPlaneMode(getApplicationContext());
		} else if (getString(R.string.tag_rotate).equalsIgnoreCase(tag)) {
			Utils.Rotation.toggleAutoOrientation(getApplicationContext());
		} else if (getString(R.string.tag_sound).equalsIgnoreCase(tag)) {
			Utils.switchSoundMode(getApplicationContext());
		}

	}

	// private void killApp(Context context) {
	// MemoryInfo before = SettingsUtils.Memory.getmMemoryInfo(this);
	// String result = AppUtils.killRunningTasks(this);
	// MemoryInfo after = SettingsUtils.Memory.getmMemoryInfo(this);
	// result = "Memory freed: "
	// + AppUtils.convertSizeIntoString(after.availMem
	// - before.availMem) + "\n" + result;
	// Toast.makeText(this, result, Toast.LENGTH_SHORT).show();
	//
	// }

	private OnClickListener mToggleListener = new OnClickListener() {

		@Override
		public void onClick(View v) {
			String tag = (String) v.getTag();
			if (getString(R.string.tag_airplane).equalsIgnoreCase(tag)) {
				Utils.Airplane.toggleAirPlaneMode(getApplicationContext());
			} else if (getString(R.string.tag_data).equalsIgnoreCase(tag)) {
				Utils.Mobile.toggleMobileData(getApplicationContext());
			} else if (getString(R.string.tag_rotate).equalsIgnoreCase(tag)) {
				Utils.Rotation.toggleAutoOrientation(getApplicationContext());
			} else if (getString(R.string.tag_wifi).equalsIgnoreCase(tag)) {
				Utils.WIFI.toggleWifi(getApplicationContext());
			} else if (getString(R.string.tag_bluetooth).equalsIgnoreCase(tag)) {
				Utils.Bluetooth.toggleBluetoothEnabled(getApplicationContext());
			}

			v.setSelected(!v.isSelected());

		}
	};

	private OnClickListener mTripleToggleListener = new OnClickListener() {

		@Override
		public void onClick(View v) {
			String tag = (String) v.getTag();
			if (getString(R.string.tag_sound).equalsIgnoreCase(tag)) {
				int state = Utils.getSoundMode(getApplicationContext());
				switch (state) {
				case AudioManager.RINGER_MODE_NORMAL:
					Utils.setSoundMode(getApplicationContext(),
							AudioManager.RINGER_MODE_SILENT);
					mImgSound.setImageResource(R.drawable.btn_volume_mute);
					break;
				case AudioManager.RINGER_MODE_SILENT:
					Utils.setSoundMode(getApplicationContext(),
							AudioManager.RINGER_MODE_VIBRATE);
					mImgSound.setImageResource(R.drawable.btn_vibrate);
					break;
				case AudioManager.RINGER_MODE_VIBRATE:
					Utils.setSoundMode(getApplicationContext(),
							AudioManager.RINGER_MODE_NORMAL);
					mImgSound.setImageResource(R.drawable.btn_volume_on);
					break;
				default:
					break;
				}
			}

		}
	};

	private OnClickListener mFavoriteClickListener = new OnClickListener() {

		@Override
		public void onClick(View v) {
			showView(mTouchIcon);
			String tag = (String) v.getTag();
			int position = Integer.valueOf(tag.substring("tag_favorite"
					.length()));
			AppInfo info = DBHelper.getInstance(getApplicationContext())
					.findFavorite(getApplicationContext(), position);
			if (null == info) {
				Bundle bundle = new Bundle();
				bundle.putInt(TouchActivity.EXTRA_PICK_APP_POSITION, position);
				TouchActivity.start(getApplicationContext(),
						TouchActivity.ACTION_PICK_APP, bundle);
			} else {
				AppUtils.launchApp(getApplicationContext(), info.pgk);
			}
		}
	};

	private OnLongClickListener mFavoriteLongClickListener = new OnLongClickListener() {

		@Override
		public boolean onLongClick(View v) {
			String tag = (String) v.getTag();
			int position = Integer.valueOf(tag.substring("tag_favorite"
					.length()));
			DBHelper.getInstance(getApplicationContext()).deleteFavorite(
					getApplicationContext(), position);
			setFavoriteApp();
			return false;
		}
	};
	private OnTouchListener mTouchIconListener = new OnTouchListener() {
		@SuppressWarnings("deprecation")
		@SuppressLint("NewApi")
		@Override
		public boolean onTouch(View v, MotionEvent event) {
			switch (event.getAction()) {
			case MotionEvent.ACTION_MOVE:
				int deltaX = (int) (event.getRawX() - mX);
				int deltaY = (int) (event.getRawY() - mY);
				mTouchIconParams.x += deltaX;
				mTouchIconParams.y += deltaY;
				mWindowManager.updateViewLayout(mTouchIcon, mTouchIconParams);
				break;
			case MotionEvent.ACTION_UP:
				int width = 0;
				int height = 0;
				Display display = mWindowManager.getDefaultDisplay();
				if (Build.VERSION.SDK_INT < 13) {
					width = display.getWidth();
					height = display.getHeight();
				} else {
					Point point = new Point();
					mWindowManager.getDefaultDisplay().getSize(point);
					width = point.x;
					height = point.y;
				}

				if (mX == width || mY == height) {
					break;
				}
				float deltaW = width - mX;
				float deltaH = height - mY;
				int newX = 0;
				int newY = 0;
				if (mX < deltaW) {
					if (mX < mY && mX < deltaH) {
						newX = getNewPosition(mTouchIconParams.x, width);
					} else {
						newY = getNewPosition(mTouchIconParams.y, height);
					}
				} else {
					if (deltaW < mY && deltaW < deltaH) {
						newX = getNewPosition(mTouchIconParams.x, width);
					} else {
						newY = getNewPosition(mTouchIconParams.y, height);
					}
				}
				animationToNewPosition(newX, newY);
			default:
				break;
			}
			mX = event.getRawX();
			mY = event.getRawY();
			return false;
		}
	};

	// private OnTouchListener mTouchViewListener = new OnTouchListener() {
	// @Override
	// public boolean onTouch(View v, MotionEvent event) {
	// switch (event.getAction()) {
	// case MotionEvent.ACTION_OUTSIDE:
	// transit(mTouchIcon, mTouchIconParams, v);
	// break;
	// default:
	// break;
	// }
	// return false;
	// }
	// };

	// ==========================================================================

	private void initUserInfo(final Context context) {
		mImgAvatar = (ImageButton) mTouchMainView
				.findViewWithTag(getString(R.string.tag_avartar));
		mTvUser = (TextView) mTouchMainView
				.findViewWithTag(getString(R.string.tag_user));
		mTvUser.setText(Build.MODEL);
		mImgAvatar.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				PackageManager pm = context.getPackageManager();

				List<ActivityManager.RunningAppProcessInfo> procList = AppUtils
						.getRunningAppProcessesList(context);
				// Retrieve running processes from ActivityManager
				ActivityManager am = (ActivityManager) getSystemService(Activity.ACTIVITY_SERVICE);
				for (ActivityManager.RunningAppProcessInfo appProcInfo : procList) {
					if ((appProcInfo != null) && (appProcInfo.pkgList != null)) {
						int size = appProcInfo.pkgList.length;
						for (int i = 0; i < size; i++) {
							// Logging.log(appProcInfo.pkgList[i]);
							ApplicationInfo appInfo = null;
							try {
								appInfo = pm
										.getApplicationInfo(
												appProcInfo.pkgList[i],
												PackageManager.GET_UNINSTALLED_PACKAGES);
								if (!appInfo.packageName.equals(context
										.getPackageName())) {
									Process.killProcess(appProcInfo.pid);
								}
								am.killBackgroundProcesses(appInfo.packageName);
								try {
									Class<?> amClass = Class.forName(am
											.getClass().getName());
									Method forceStopPackage = amClass
											.getDeclaredMethod(
													"forceStopPackage",
													String.class);
									forceStopPackage.setAccessible(true);
									forceStopPackage.invoke(am,
											appInfo.packageName);
								} catch (Exception e) {
									Logging.log(e);
								}
							} catch (NameNotFoundException e) {
								continue;
							}

						}
					}
				}
			}
		});
	}

	private void loadInstallApp(Context context) {
		mLvInstalledApps = (ListView) mTouchMainView
				.findViewWithTag(getString(R.string.tag_list));
		mInstalledApps = new ArrayList<AppInfo>();
		PackageManager pm = context.getPackageManager();
		ArrayList<ApplicationInfo> apps = (ArrayList<ApplicationInfo>) pm
				.getInstalledApplications(PackageManager.GET_UNINSTALLED_PACKAGES);
		String ownPgk = context.getPackageName();
		for (ApplicationInfo app : apps) {
			Intent intent = pm.getLaunchIntentForPackage(app.packageName);
			if (intent != null && !ownPgk.equals(app.packageName)) {
				AppInfo appInfo = new AppInfo(app.packageName, app
						.loadLabel(pm).toString(), app.loadIcon(pm),
						(app.flags & ApplicationInfo.FLAG_SYSTEM) != 0);
				mInstalledApps.add(appInfo);
			}
		}
		Collections.sort(mInstalledApps, new Comparator<AppInfo>() {

			@Override
			public int compare(AppInfo lhs, AppInfo rhs) {
				return lhs.name.compareToIgnoreCase(rhs.name);
			}
		});

		mLvInstalledApps.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				Logging.log(parent);

			}
		});
		mAdtInstalledApps = new AppsAdapter(context, mInstalledApps,
				R.layout.row_common);
		mLvInstalledApps.setAdapter(mAdtInstalledApps);

	}

	private void loadRunningApp(Context context) {
		mRunningApps = new ArrayList<AppInfo>();
		// mLvRunningApps = (HorizontalListView) mTouchMainView
		// .findViewWithTag(getString(R.string.tag_runing_app));
		mAdtRunningApps = new AppsAdapter(getApplicationContext(),
				mRunningApps, R.layout.row_common);
		PackageManager pm = context.getPackageManager();
		ActivityManager am = (ActivityManager) context
				.getSystemService(Context.ACTIVITY_SERVICE);
		List<RunningAppProcessInfo> runningInfos = am.getRunningAppProcesses();
		// Retrieve running processes from ActivityManager
		for (ActivityManager.RunningAppProcessInfo appProcInfo : runningInfos) {
			if ((appProcInfo != null) && (appProcInfo.pkgList != null)) {
				int size = appProcInfo.pkgList.length;
				for (int i = 0; i < size; i++) {
					ApplicationInfo appInfo = null;
					try {
						appInfo = pm.getApplicationInfo(appProcInfo.pkgList[i],
								PackageManager.GET_UNINSTALLED_PACKAGES);
					} catch (NameNotFoundException e) {
						continue;
					}
					if (appInfo != null) {
						Logging.log(appInfo.loadLabel(pm));
						mRunningApps
								.add(new AppInfo(
										appInfo.packageName,
										appInfo.loadLabel(pm).toString(),
										appInfo.loadIcon(pm),
										(appInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0));
					}
				}
			}
		}

		// mLvRunningApps.setAdapter(mAdtRunningApps);

	}

	private void loadRecentApp(Context context) {
		mLvInstalledApps = (ListView) mTouchMainView
				.findViewWithTag(getString(R.string.tag_list));
		mInstalledApps = new ArrayList<AppInfo>();
		ActivityManager am = (ActivityManager) context
				.getSystemService(Context.ACTIVITY_SERVICE);
		List<ActivityManager.RecentTaskInfo> taskInfos = am.getRecentTasks(
				Integer.MAX_VALUE, ActivityManager.RECENT_WITH_EXCLUDED);
		PackageManager pm = context.getPackageManager();
		String ownPgk = context.getPackageName();
		for (RecentTaskInfo recentTaskInfo : taskInfos) {
			ComponentName componentName = recentTaskInfo.baseIntent
					.getComponent();
			Intent baseIntent = recentTaskInfo.baseIntent;
			if (!componentName.getPackageName().equals(ownPgk)) {
				AppInfo appInfo = new AppInfo(componentName.getPackageName(),
						AppUtils.getApplicationLabel(getApplicationContext(),
								componentName.getPackageName()),
						AppUtils.getApplicationIcon(getApplicationContext(),
								componentName.getPackageName()), baseIntent,
						componentName, true);
				mInstalledApps.add(appInfo);
			}
		}
		// for (ApplicationInfo app : apps) {
		// Intent intent = pm.getLaunchIntentForPackage(app.packageName);
		// if (intent != null && !ownPgk.equals(app.packageName)) {
		// AppInfo appInfo = new AppInfo(app.packageName, app
		// .loadLabel(pm).toString(), app.loadIcon(pm),
		// (app.flags & ApplicationInfo.FLAG_SYSTEM) != 0);
		// mInstalledApps.add(appInfo);
		// }
		// }
		Collections.sort(mInstalledApps, new Comparator<AppInfo>() {

			@Override
			public int compare(AppInfo lhs, AppInfo rhs) {
				return lhs.name.compareToIgnoreCase(rhs.name);
			}
		});

		mLvInstalledApps.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				Logging.log(parent);

			}
		});
		mAdtInstalledApps = new AppsAdapter(context, mInstalledApps,
				R.layout.row_common);
		mLvInstalledApps.setAdapter(mAdtInstalledApps);

	}

	@SuppressLint("NewApi")
	private void init() {
		mWindowManager = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
		mFlagWindow = LayoutParams.FLAG_LAYOUT_IN_SCREEN
				| LayoutParams.FLAG_NOT_FOCUSABLE
				| LayoutParams.FLAG_NOT_TOUCH_MODAL
				| LayoutParams.FLAG_TURN_SCREEN_ON
				| LayoutParams.FLAG_SHOW_WHEN_LOCKED
				| LayoutParams.FLAG_WATCH_OUTSIDE_TOUCH;
		mTouchIconParams = new LayoutParams(LayoutParams.WRAP_CONTENT,
				LayoutParams.WRAP_CONTENT, 0, 0,
				LayoutParams.TYPE_SYSTEM_ERROR, mFlagWindow,
				PixelFormat.TRANSLUCENT);
		mTouchViewParams = new LayoutParams(LayoutParams.WRAP_CONTENT,
				LayoutParams.WRAP_CONTENT, 0, 0,
				LayoutParams.TYPE_SYSTEM_ERROR, mFlagWindow,
				PixelFormat.TRANSLUCENT);

		mTouchViewParams.gravity = Gravity.CENTER;
		mTouchIcon = LayoutInflater.from(getApplicationContext()).inflate(
				R.layout.view_touch_icon, null);
		((ImageButton) mTouchIcon).setImageResource(CONFIG.FLOAT_ICON
				.getFloatIcon(this));
		mTouchMainView = LayoutInflater.from(getApplicationContext()).inflate(
				R.layout.view_touch_pager, null);
		// setMainViewParams();
		mTouchMainView.setOnTouchListener(new OnTouchListener() {

			private float lastX;
			private float initialX;

			@Override
			public boolean onTouch(View v, MotionEvent touchevent) {
				switch (touchevent.getAction()) {
				case MotionEvent.ACTION_DOWN:
					initialX = touchevent.getX();
					break;
				case MotionEvent.ACTION_MOVE:
					break;
				case MotionEvent.ACTION_UP:
					float finalX = touchevent.getX();
					if (initialX > finalX) {
						((ViewFlipper) mTouchMainView).setInAnimation(
								TouchService.this, R.anim.in_right);
						((ViewFlipper) mTouchMainView).setOutAnimation(
								TouchService.this, R.anim.out_left);

						if (((ViewFlipper) mTouchMainView).getDisplayedChild() == 2) {
							((ViewFlipper) mTouchMainView).setDisplayedChild(0);
							break;
						}

						((ViewFlipper) mTouchMainView).showNext();
					} else {
						((ViewFlipper) mTouchMainView).setInAnimation(
								TouchService.this, R.anim.in_left);
						((ViewFlipper) mTouchMainView).setOutAnimation(
								TouchService.this, R.anim.out_right);
						if (((ViewFlipper) mTouchMainView).getDisplayedChild() == 0) {
							((ViewFlipper) mTouchMainView).setDisplayedChild(2);
							break;
						}

						((ViewFlipper) mTouchMainView).showPrevious();
					}
					break;
				case MotionEvent.ACTION_OUTSIDE:
					showView(mTouchIcon);
					break;
				}
				return false;
			}
		});
		mWindowManager.addView(mTouchIcon, mTouchIconParams);
		mWindowManager.addView(mTouchMainView, mTouchViewParams);
		mTouchMainView.setVisibility(View.GONE);
		mTouchIcon.setOnTouchListener(mTouchIconListener);
		mTouchIcon.setOnLongClickListener(this);
		((ImageButton) mTouchIcon).setOnClickListener(this);
		// MAIN
		DBHelper dbHelper = DBHelper.getInstance(TouchService.this);
		loadMain(mTouchMainView);
		loadSub(mTouchMainView);
		mImgAirplane = (ImageButton) mTouchMainView
				.findViewWithTag(getString(R.string.tag_airplane));
		// mImgAirplane.setOnClickListener(mToggleListener);
		// ((ImageButton) mTouchMainView
		// .findViewWithTag(getString(R.string.tag_back)))
		// .setOnClickListener(this);
		mImgBluetooth = (ImageButton) mTouchMainView
				.findViewWithTag(getString(R.string.tag_bluetooth));
		// mImgBluetooth.setOnClickListener(mToggleListener);

		// ((ImageButton) mTouchMainView
		// .findViewWithTag(getString(R.string.tag_camera)))
		// .setOnClickListener(this);
		mImgData = (ImageButton) mTouchMainView
				.findViewWithTag(getString(R.string.tag_data));
		// if (SettingsUtils.canToggleMobileData(getApplicationContext())) {
		// mImgData.setOnClickListener(mToggleListener);
		// } else {
		// mImgData.setOnClickListener(this);
		// }
		//
		mImgGps = (ImageButton) mTouchMainView
				.findViewWithTag(getString(R.string.tag_gps));
		// mImgGps.setOnClickListener(this);

		// ((ImageButton) mTouchMainView
		// .findViewWithTag(getString(R.string.tag_help)))
		// .setOnClickListener(this);
		// ((ImageButton) mTouchMainView
		// .findViewWithTag(getString(R.string.tag_mirror)))
		// .setOnClickListener(this);
		// ((ImageButton) mTouchMainView
		// .findViewWithTag(getString(R.string.tag_light)))
		// .setOnClickListener(this);
		//
		mImgRotate = (ImageButton) mTouchMainView
				.findViewWithTag(getString(R.string.tag_rotate));
		// mImgRotate.setOnClickListener(mToggleListener);

		mImgWifi = (ImageButton) mTouchMainView
				.findViewWithTag(getString(R.string.tag_wifi));
		// mImgWifi.setOnClickListener(mToggleListener);
		mImgSound = (ImageButton) mTouchMainView
				.findViewWithTag(getString(R.string.tag_sound));
		// mImgSound.setOnClickListener(mTripleToggleListener);
		// ((ImageButton) mTouchMainView
		// .findViewWithTag(getString(R.string.tag_settings)))
		// .setOnClickListener(this);
		// ((ImageButton) mTouchMainView
		// .findViewWithTag(getString(R.string.tag_folder)))
		// .setOnClickListener(this);
		for (int i = 0; i < MAX_9_APPS; i++) {
			ImageButton imgFav = (ImageButton) mTouchMainView
					.findViewWithTag(getString(R.string.tag_favorite) + i);
			imgFav.setOnClickListener(mFavoriteClickListener);
			imgFav.setOnLongClickListener(mFavoriteLongClickListener);
		}
		setState();
		setFavoriteApp();

		// loadInstallApp(TouchService.this);
		// loadRecentApp(getApplicationContext());
		// loadRunningApp(getApplicationContext());
		// initUserInfo(TouchService.this);
	}

	private void loadSub(View rootView) {
		DBHelper dbHelper = DBHelper.getInstance(this);
		for (int i = 0; i < 12; i++) {
			int id = getResources().getIdentifier("imgsub" + i, "id",
					this.getPackageName());
			ImageButton view = (ImageButton) rootView.findViewById(id);
			FloatInfo info = dbHelper.findSettings(this, i);
			if (info != null) {

				view.setTag(info.tag);
				view.setImageResource(info.resource);
				view.setOnClickListener(this);
				view.setVisibility(View.VISIBLE);
			} else {
				view.setVisibility(View.GONE);
			}
		}

	}

	private void loadMain(View rootView) {
		DBHelper dbHelper = DBHelper.getInstance(this);
		for (int i = 0; i < 9; i++) {
			int id = getResources().getIdentifier("img" + i, "id",
					this.getPackageName());
			ImageButton view = (ImageButton) rootView.findViewById(id);
			FloatInfo info = dbHelper.findMain(this, i);
			if (info != null) {
				view.setTag(info.tag);
				view.setImageResource(info.resource);
				view.setOnClickListener(this);
				view.setVisibility(View.VISIBLE);
			} else {
				view.setVisibility(View.GONE);
			}
		}

	}

	private void setState() {
		mImgAirplane.setSelected(Utils
				.Airplane.isAirPlaneModeEnable(getApplicationContext()));
		mImgBluetooth.setSelected(Utils.Bluetooth
				.isBluetoothEnabled(getApplicationContext()));
		mImgGps.setSelected(Utils.GPS.isGpsEnabled(getApplicationContext()));
		mImgRotate.setSelected(Utils
				.Rotation.isAutoOrientationEnabled(getApplicationContext()));
		mImgWifi.setSelected(Utils
				.WIFI.isWifiEnabled(getApplicationContext()));
		mImgData.setSelected(Utils
				.Mobile.isMobileDataEnabled(getApplicationContext()));
		switch (Utils.getSoundMode(getApplicationContext())) {
		case AudioManager.RINGER_MODE_NORMAL:
			mImgSound.setImageResource(R.drawable.btn_volume_on);
			break;
		case AudioManager.RINGER_MODE_SILENT:
			mImgSound.setImageResource(R.drawable.btn_volume_mute);
			break;
		case AudioManager.RINGER_MODE_VIBRATE:
			mImgSound.setImageResource(R.drawable.btn_vibrate);
			break;
		default:
			break;
		}
	}

	private void startForeGroundService() {
		// android.support.v4.app.NotificationCompat.Builder builder = new
		// android.support.v4.app.NotificationCompat.Builder(
		// TouchService.this);
		// Intent intent = new Intent(getApplicationContext(),
		// TouchActivity.class);
		// intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK
		// | IntentCompat.FLAG_ACTIVITY_CLEAR_TASK);
		// PendingIntent pendingIntent = PendingIntent.getActivity(
		// TouchService.this, 1000, intent,
		// PendingIntent.FLAG_UPDATE_CURRENT);
		// builder.addAction(R.drawable.ic_android, "Android Touch",
		// pendingIntent);
		// startForeground(1000, builder.build());

		android.support.v4.app.NotificationCompat.Builder builder = new android.support.v4.app.NotificationCompat.Builder(
				TouchService.this);
		builder.setContentText(getString(R.string.app_name));
		builder.setContentTitle(getString(R.string.app_name));
		builder.setAutoCancel(false);
		builder.setContentIntent(PendingIntent.getActivity(this, 0, new Intent(
				this, TouchActivity.class)
				.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK
						| IntentCompat.FLAG_ACTIVITY_CLEAR_TASK), 0));
		builder.setSmallIcon(R.drawable.ic_android0);
		Notification notif = builder.build();
		startForeground(8001, notif);

	}

	@SuppressLint("NewApi")
	// private void transit(View addedView, LayoutParams addedParam,
	// View... removedView) {
	//
	// for (View view : removedView) {
	// try {
	// mWindowManager.removeView(view);
	// } catch (Exception e) {
	// Logging.log(e);
	// }
	// }
	//
	// try {
	// mWindowManager.addView(addedView, addedParam);
	// } catch (Exception e) {
	// Logging.log(e);
	// }
	// if (addedView == mTouchMainView) {
	// setState();
	// } else if (addedView == mTouchMainView) {
	// setFavoriteApp();
	// }
	// DBHelper dbHelper = DBHelper.getInstance(TouchService.this);
	// for (int i = 0; i < MAX_FAV_APPS; i++) {
	// FloatInfo info = dbHelper.findMain(TouchService.this, i);
	// if (info != null) {
	// ImageButton view = (ImageButton) mTouchMainView
	// .findViewWithTag(info.tag);
	// view.setImageResource(info.resource);
	// ObjectAnimator animator = new ObjectAnimator();
	// animator.setPropertyName("rotationY");
	// animator.setDuration(2000);
	// animator.setFloatValues(0, 180);
	// animator.setTarget(view);
	// animator.start();
	// view.setOnClickListener(this);
	// }
	// }
	// }
	private int getNewPosition(int curDimension, int maxDimension) {
		if (curDimension > 0) {
			return maxDimension / 2;
		} else {
			return -maxDimension / 2;
		}
	}

	private void setFavoriteApp() {
		for (int i = 0; i < MAX_9_APPS; i++) {
			AppInfo info = DBHelper.getInstance(getApplicationContext())
					.findFavorite(getApplicationContext(), i);
			ImageButton fav = (ImageButton) mTouchMainView
					.findViewWithTag(getString(R.string.tag_favorite) + i);
			if (null == info) {
				fav.setImageResource(R.drawable.btn_add);
			} else {
				fav.setImageDrawable(AppUtils.getApplicationIcon(
						getApplicationContext(), info.pgk));
			}
		}
	}

	private void animationToNewPosition(final int newX, final int newY) {
		if (newX != 0) {
			int curX = mTouchIconParams.x;
			final int deltaX = (newX - curX) / 20;
			new CountDownTimer(200, 10) {

				@Override
				public void onTick(long millisUntilFinished) {
					try {
						mTouchIconParams.x += deltaX;
						mWindowManager.updateViewLayout(mTouchIcon,
								mTouchIconParams);
					} catch (Exception e) {
						cancel();
					}

				}

				@Override
				public void onFinish() {
					try {
						mTouchIconParams.x = newX;
						mWindowManager.updateViewLayout(mTouchIcon,
								mTouchIconParams);
					} catch (Exception e) {
						cancel();
					}
				}

			}.start();
			return;
		}

		if (newY != 0) {
			int curY = mTouchIconParams.y;
			final int deltaY = (newY - curY) / 20;
			new CountDownTimer(200, 10) {

				@Override
				public void onTick(long millisUntilFinished) {
					try {
						mTouchIconParams.y += deltaY;
						mWindowManager.updateViewLayout(mTouchIcon,
								mTouchIconParams);
					} catch (Exception e) {
						cancel();
					}

				}

				@Override
				public void onFinish() {
					try {
						mTouchIconParams.y = newY;
						mWindowManager.updateViewLayout(mTouchIcon,
								mTouchIconParams);
					} catch (Exception e) {
						cancel();
					}

				}
			}.start();

		}

	}

	// ==========================================================================
	private class AppsAdapter extends BaseAdapter {
		private Context context;
		private ArrayList<AppInfo> applications;
		private int resId;

		public AppsAdapter(Context context, ArrayList<AppInfo> applications,
				int resId) {
			super();
			this.context = context;
			this.applications = applications;
			this.resId = resId;
		}

		@Override
		public int getCount() {
			return applications.size();
		}

		@Override
		public Object getItem(int position) {
			return applications.get(position);
		}

		@Override
		public long getItemId(int position) {
			return position;
		}

		@Override
		public View getView(final int position, View convertView,
				ViewGroup parent) {
			Holder holder;
			if (null == convertView) {
				convertView = LayoutInflater.from(context).inflate(resId, null);
				holder = new Holder();
				holder.tvName = (TextView) convertView.findViewWithTag(context
						.getString(R.string.tag_name));
				convertView.setTag(holder);
			} else {
				holder = (Holder) convertView.getTag();
			}
			AppInfo application = applications.get(position);
			holder.tvName.setText(application.name);
			Drawable icon = application.icon;
			icon.setBounds(0, 0, 48, 48);
			holder.tvName.setCompoundDrawables(icon, null, null, null);
			convertView.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					// AppUtils.launchApp(context,
					// applications.get(position).pgk);
					// startActivity(applications.get(position).baseIntent);

				}
			});
			return convertView;
		}
	}

	private static class Holder {
		TextView tvName;
	}

	private void setMainViewParams() {
		Display display = mWindowManager.getDefaultDisplay();
		int deviceH = display.getHeight();
		int deviceW = display.getWidth();
		int h;
		int w;
		int orientation = getResources().getConfiguration().orientation;
		switch (orientation) {
		case Configuration.ORIENTATION_LANDSCAPE:
			h = deviceH * 3 / 4;
			w = deviceW * 3 / 4;
			break;
		default:
			h = deviceH * 2 / 3;
			w = deviceW * 5 / 6;
			break;
		}
		if (h > MAX_TASKBAR_HEIGHT) {
			h = MAX_TASKBAR_HEIGHT;
		}
		if (h / 1.5 > w) {
			h = (int) (w * 1.5);
		} else {
			w = (int) (h / 1.5);
		}
		mTouchViewParams.height = h;
		mTouchMainView.findViewWithTag(getString(R.string.tag_menubar));
		android.view.ViewGroup.LayoutParams params = mTouchMainView
				.findViewWithTag(getString(R.string.tag_menubar))
				.getLayoutParams();
		params.width = w;
		// LayoutParams params = (LayoutParams)
		// mTouchMainView.findViewWithTag(getString(R.string.tag_menubar)).getLayoutParams();
		// params.width = w;

		// mTouchViewParams.width = w;

	}

	private void removeAllView() {
		try {
			mWindowManager.removeView(mTouchMainView);
		} catch (Exception e) {
		}

		try {
			mWindowManager.removeView(mTouchIcon);
		} catch (Exception e) {
		}
	}

	@Override
	public boolean onLongClick(View v) {
		String tag = (String) v.getTag();
		if (getString(R.string.tag_icon).equals(tag)) {
			TouchActivity.start(this);
		}
		return true;
	}

}
